package org.misalen.web.support.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.imageio.ImageIO;

/**
 * 图片水印
 * 
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
public class ImageMarkUtil {

	public static Image url2Image(String urlString) {
		try {
			URL url = new URL(urlString);
			Image userImg = ImageIO.read(url);
			return userImg;
		} catch (Exception e) {
			System.err.println(e);
		}
		return null;
	}

	public static void saveImg(Image iamge, String path) {
		int width = iamge.getWidth(null);
		int height = iamge.getHeight(null);
		BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = buffImg.createGraphics();
		buffImg = graphics2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		graphics2d = buffImg.createGraphics();
		graphics2d.drawImage(iamge, 0, 0, null);
		graphics2d.dispose();
		saveImg(buffImg, path);
	}

	public static void saveImg(BufferedImage buffImg, String path) {
		OutputStream os = null;
		try {
			os = new FileOutputStream(path);
			ImageIO.write(buffImg, "PNG", os);
		} catch (Exception e) {
			System.err.println(e);
		} finally {
			try {
				os.close();
			} catch (Exception e) {
				System.err.println(e);
			}
		}
	}

	/**
	 * 
	 * 拼图
	 * 
	 * @param topImgUrl
	 *            上层图片地址
	 * @param downImgUrl
	 *            下层图片地址
	 * @param location
	 *            位置
	 * @param overflow
	 *            溢出值
	 * @return
	 */
	public static BufferedImage jointImage(Image topImg, Image downImg) {
		try {
			int width = Math.min(downImg.getWidth(null), topImg.getWidth(null));
			int height = Math.min(downImg.getHeight(null), topImg.getHeight(null));
			BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2d = buffImg.createGraphics();
			buffImg = graphics2d.getDeviceConfiguration().createCompatibleImage(width, height,
					Transparency.TRANSLUCENT);
			graphics2d = buffImg.createGraphics();
			graphics2d.drawImage(downImg.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
			graphics2d.drawImage(topImg.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
			graphics2d.dispose();
			return buffImg;
		} catch (Exception e) {
			System.err.println(e);
		}
		return null;

	}

}
